
package x.trident.core.email.starter;

import cn.hutool.extra.mail.MailAccount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import x.trident.core.email.api.EmailConfigApi;
import x.trident.core.email.api.MailSenderApi;
import x.trident.core.email.jdk.DefaultEmailConfigImpl;
import x.trident.core.email.jdk.JavaMailSender;

/**
 * 邮件发送的自动配置类
 *
 * @author 林选伟
 * @date 2020/12/1 11:25
 */
@Configuration
@Slf4j
public class TridentEmailAutoConfiguration {

    /**
     * 默认的邮箱配置实现
     */
    @Bean
    @ConditionalOnMissingBean(EmailConfigApi.class)
    public EmailConfigApi emailConfigApi() {
        return new DefaultEmailConfigImpl();
    }

    /**
     * java mail方式发送邮件的接口
     */
    @Bean
    @ConditionalOnMissingBean(MailSenderApi.class)
    public MailSenderApi mailSenderApi(EmailConfigApi emailConfigApi) {
        MailAccount mailAccount = new MailAccount();

        // 配置默认都从系统配置表获取
        mailAccount.setHost(emailConfigApi.getSmtpHost());
        mailAccount.setPort(emailConfigApi.getSmtpPort());
        mailAccount.setAuth(emailConfigApi.getSmtpAuthEnable());
        mailAccount.setUser(emailConfigApi.getSmtpUser());
        mailAccount.setPass(emailConfigApi.getSmtpPass());
        mailAccount.setFrom(emailConfigApi.getSmtpFrom());
        mailAccount.setStarttlsEnable(emailConfigApi.getStartTlsEnable());
        mailAccount.setSslEnable(emailConfigApi.getSSLEnable());
        mailAccount.setSocketFactoryPort(emailConfigApi.getSocketFactoryPort());
        mailAccount.setTimeout(emailConfigApi.getTimeout());
        mailAccount.setConnectionTimeout(emailConfigApi.getConnectionTimeout());

        return new JavaMailSender(mailAccount);
    }

}
